﻿using System;
using System.IO;
using System.Text;
using System.Web.Mvc;

namespace ASP.NET_MVC_Static_Test
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
    public class StaticFileHandlerFilterAttribute: ActionFilterAttribute
    {

        private object lockobject = new object();

        private object lockobject2 = new object();
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            //获取结果
            ActionResult actionResult = context.Result;
            //判断结果是否是一个ViewResult
            if (actionResult is ViewResult)
            {
                //获取路由信息
                string controllerName = context.RouteData.Values["controller"].ToString().ToLower();
                string actionName = context.RouteData.Values["action"].ToString().ToLower();
                string webdomain = context.RouteData.Values.ContainsKey("webdomain") ? context.RouteData.Values["webdomain"].ToString() : "";

                var result = ViewEngines.Engines.FindView(context, actionName, null);
                var builder = new StringBuilder();
                using (var writer = new StringWriter(builder))
                {
                    ViewContext viewContext = new ViewContext(context, result.View, context.Controller.ViewData, context.Controller.TempData, writer);
                    result.View.Render(viewContext, writer);
                    writer.Flush();
                    //var strResultHtml = writer.ToString();
                }
                string devicedir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "StaticView", controllerName, actionName, webdomain);
                if (!Directory.Exists(devicedir))
                {
                    Directory.CreateDirectory(devicedir);
                }

                //写入文件
                string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "StaticView", controllerName, actionName, webdomain, "Index.html");
                lock (lockobject2)
                {
                    using (FileStream fs = File.Open(filePath, FileMode.Create))
                    {
                        using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
                        {
                            sw.Write(builder.ToString());
                        }
                    }
                }
                //输出当前的结果
                ContentResult contentresult = new ContentResult();
                contentresult.Content = builder.ToString();
                contentresult.ContentType = "text/html";
                context.Result = contentresult;
                //context.RequestContext.HttpContext.Response.Redirect("www.baidu.com");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            //获取路由信息
            var controllerName = context.RouteData.Values["controller"].ToString().ToLower();
            var actionName = context.RouteData.Values["action"].ToString().ToLower();
            string webdomain = context.RouteData.Values.ContainsKey("webdomain") ? context.RouteData.Values["webdomain"].ToString() : "";
            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "StaticView", controllerName, actionName, webdomain, "Index.html");

            //获取文件信息对象
            FileInfo fileInfo = new FileInfo(filePath);
            //获取时间间隔
            TimeSpan ts = DateTime.Now - fileInfo.LastWriteTime;
            if (ts.TotalMinutes <= 2)
            {
                //判断文件是否存在
                if (File.Exists(filePath))
                {
                    lock (lockobject)
                    {
                        //如果存在，直接读取文件
                        using (FileStream fs = File.Open(filePath, FileMode.Open))
                        {
                            using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
                            {
                                //通过contentresult返回文件内容
                                ContentResult contentresult = new ContentResult();
                                contentresult.Content = sr.ReadToEnd();
                                contentresult.ContentType = "text/html";
                                context.Result = contentresult;
                            }
                        }
                    }
                    //context.RequestContext.HttpContext.Response.Redirect("www.baidu.com");
                }
            }
            
        }
    }
}